package com.keepers.repair.fragment

import android.Manifest
import android.annotation.SuppressLint
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import com.google.gson.Gson
import com.keepers.repair.R
import com.keepers.repair.activity.ChatActivity
import com.keepers.repair.adapter.ChatHistoryAdapter
import com.keepers.repair.aidl.IMainCallback
import com.keepers.repair.model.ChatHistoryItemModel
import com.keepers.repair.model.SocketMessageModel
import com.keepers.repair.model.UserModel
import com.keepers.repair.utils.Api
import com.keepers.repair.utils.encodeBase64File
import com.keepers.repair.utils.getDateString
import com.keepers.repair.utils.getUser
import org.jetbrains.anko.find
import org.jetbrains.anko.support.v4.alert
import org.jetbrains.anko.support.v4.toast
import pub.devrel.easypermissions.EasyPermissions
import java.io.File
import java.util.*


class ChatContentFragment : Fragment(), EasyPermissions.PermissionCallbacks {

    private lateinit var recyclerView: RecyclerView
    private lateinit var editText: EditText
    private lateinit var sendButton: Button
    private lateinit var changeButton: Button
    private lateinit var recordButton: Button
    private lateinit var textView: LinearLayout
    private lateinit var recordView: LinearLayout
    private var currentFileName = ""
    private var messages = mutableListOf<ChatHistoryItemModel>()
    private var recorder = MediaRecorder()
    private val permissionList = arrayOf(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.RECORD_AUDIO
    )
    private var isTextView: Boolean = true
        set(value) {
            if(value) {
                textView.visibility = View.VISIBLE
                recordView.visibility = View.GONE
            } else {
                textView.visibility = View.GONE
                recordView.visibility = View.VISIBLE
            }
        }

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_chat_content, container, false)

        recyclerView = view.find(R.id.chat_content_recycler_view)
        editText = view.find(R.id.chat_content_edit_text)
        sendButton = view.find(R.id.chat_content_send_button)
        changeButton = view.find(R.id.chat_content_change_button)
        recordButton = view.find(R.id.chat_content_record_button)
        textView = view.find(R.id.chat_content_text_view)
        recordView = view.find(R.id.chat_content_record_view)

        isTextView = true
        setSendButton(sendButton, false)
        changeButton.setOnClickListener {
            isTextView = true
        }
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {}
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
            override fun onTextChanged(text: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (text.isNullOrEmpty()) {
                    setSendButton(sendButton, false)
                } else {
                    setSendButton(sendButton, true)
                }
            }
        })
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = ChatHistoryAdapter(messages)
        recordButton.setOnTouchListener { _, motionEvent ->
            when(motionEvent.action) {
                MotionEvent.ACTION_DOWN -> {
                    println("down")
                    recordStart()
                }
                MotionEvent.ACTION_UP -> {
                    println("up")
                    recordEnd()
                }
            }
            true
        }
        return view
    }

    override fun onResume() {
        super.onResume()
        val activity = activity as ChatActivity?
        val service = activity?.service
        val handler = Handler()
        service?.setReceivedCallback(object : IMainCallback.Stub() {
            override fun callback(msg: String?): Boolean {
                try {
                    val message = Gson().fromJson<SocketMessageModel>(msg, SocketMessageModel::class.java)
                    val item = ChatHistoryItemModel(
                        Name = message.FromUserName,
                        DataType = message.MsgType,
                        ChattingContent = message.Content,
                        ChattingDate = message.CreateTime
                    )
                    handler.post {
                        messages.add(item)
                        recyclerView.adapter?.notifyDataSetChanged()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                return true
            }
        })
        if (! EasyPermissions.hasPermissions(context!!, *permissionList)) {
            EasyPermissions.requestPermissions(this, "使用需要您的授权，是否开启授权？",
                0, *permissionList)
        }
    }

    override fun onPause() {
        super.onPause()
        val service = (activity as ChatActivity).service
        service?.clearReceivedCallback()
    }

    @SuppressLint("ResourceAsColor")
    private fun setSendButton(button: Button, isSend: Boolean) {
        if (isSend) {
            button.text = "发送"
            button.setOnClickListener { sendMessage() }
        } else {
            button.text = "语音"
            button.setOnClickListener { isTextView = false }
        }
    }

    private fun send(content: String, type: String) {
        val service = (activity as ChatActivity).service
        var user: UserModel? = null
        context?.apply {
            user = getUser(this) ?: return
        }
        service?.sendMessage(editText.text.toString())
        messages.add(ChatHistoryItemModel(
            Name=user!!.Name!!,
            DataType=type,
            ChattingDate= getDateString(),
            ChattingContent=content
        ))
        recyclerView.adapter?.notifyDataSetChanged()
        editText.text.clear()
        Log.d("Hell", "sendMessage")
    }

    private fun sendMessage() {
        val content = editText.text.toString()
        send(content, "Text")
    }

    private fun sendVoice(path: String) {
        val service = (activity as ChatActivity).service
        send(path, "Voice")
        service?.sendVoice(path)
    }

    private fun recordStart() {
        val time = Date().time
        val random = Random().nextInt(9999)
        val cacheDir = context?.cacheDir
        val fileName = "$cacheDir${File.separator}$time-$random.amr"
        currentFileName = fileName
        Log.d("hell", "file name: $fileName")
        recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT)
        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB)
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
        recorder.setOutputFile(fileName)
        recorder.prepare()
        recorder.start()
    }

    private fun recordEnd() {
        recorder.stop()
        recorder.reset()
        val str = encodeBase64File(currentFileName)
        val user = getUser(context!!)
        Log.d("Hell", str)
        user?.apply {
            val fileName = currentFileName.split(File.separator).last()
            Api.uploadChatVoice(user.Gid, user.GroupGid!!, str, fileName, 12) { result ->
                if (result == null) {
                    toast("上传错误，请重试")
                } else {
                    sendVoice(result)
                }
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {}
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        this.alert(message = "无法获取授权") {
            isCancelable = false
        }.show()
    }
}
